//
//  StatisticsViewController.m
//  quickBatchManager
//
//  Created by jack on 15/10/14.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "StatisticsViewController.h"
#import "PMCalendar.h"
@interface StatisticsViewController ()<PMCalendarControllerDelegate>
{
    UITableView *mTableView;
    NSMutableArray *array;
    UILabel *countLabel;
    int timePos;
    NSMutableArray *datas;
    NSDate *startDate;
    NSDate *endDate;
}
@property (nonatomic, strong) PMCalendarController *pmCC;
@end

@implementation StatisticsViewController
@synthesize pieChartLeft,pmCC;
- (void)viewDidLoad {
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [self setPieChartLeft:nil];
    [super viewDidUnload];
}

-(void)initData
{
    datas = [NSMutableArray array];
    startDate = [NSDate date];
    endDate = [NSDate date];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.pieChartLeft reloadData];
    [mTableView reloadData];
}

-(void)initUI
{
    int total = 0;
    for (int i=0; i<array.count; i++) {
        PayModel *model = [array objectAtIndex:i];
        total +=model.money;
    }
    
    self.sliceColors =[NSArray arrayWithObjects:
                       [UIColor colorWithRed:246/255.0 green:155/255.0 blue:0/255.0 alpha:1],
                       [UIColor greenColor],
                       [UIColor blueColor],nil];
    
    [_backBtn bk_whenTapped:^{
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIImage *image = _bgImageView.image;
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    _bgImageView.image=image;
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(7, 45, _bgImageView.frame.size.width-14, 40)];
    [titleView setBackgroundColor:FONT_COLOR_GRAY];
    [_bgImageView addSubview:titleView];

    UILabel *detailsLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 120, 40)];
    [detailsLabel setTextAlignment:NSTextAlignmentCenter];
    detailsLabel.text = @"详细";
    UILabel *fenleiLabel = [[UILabel alloc] initWithFrame:CGRectMake(125, 0, 120, 40)];
    [fenleiLabel setTextAlignment:NSTextAlignmentCenter];
    fenleiLabel.text = @"分类";
    UILabel *moneyLabel = [[UILabel alloc] initWithFrame:CGRectMake(240, 0, 110, 40)];
    [moneyLabel setTextAlignment:NSTextAlignmentCenter];
    moneyLabel.text = @"金额";
    
    [titleView addSubview:detailsLabel];
    [titleView addSubview:fenleiLabel];
    [titleView addSubview:moneyLabel];
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(titleView.frame), _bgImageView.frame.size.width-20, _bgImageView.frame.size.height-50)];
    mTableView.dataSource = self;
    [_bgImageView addSubview:mTableView];
    
    countLabel = [[UILabel alloc] initWithFrame:CGRectMake(35,  CGRectGetMaxY(mTableView.frame)+marginSize, 100, 30)];
    countLabel.text = [NSString stringWithFormat:@"合计:%d",total];
    [_bgImageView addSubview:countLabel];
    
    UIButton *detailsBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(mTableView.frame)-110, CGRectGetMaxY(mTableView.frame)+5, 100, 40)];
    [detailsBtn setBackgroundImage:[UIImage imageNamed:@"hongdi"] forState:UIControlStateNormal];
    [_bgImageView addSubview:detailsBtn];
    
    UILabel *deLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    deLabel.text = @"详情";
    [deLabel setTextAlignment:NSTextAlignmentCenter];
    [deLabel setTextColor:[UIColor whiteColor]];
    [detailsBtn addSubview:deLabel];
    deLabel.userInteractionEnabled = YES;
    
    [detailsBtn bk_whenTapped:^{
        NSLog(@"详情");
        PayListViewController *payListVC = [[PayListViewController alloc] init];
        payListVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        payListVC.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
        self.definesPresentationContext = YES;
        [self presentViewController:payListVC animated:YES completion:nil];
    }];
    
    
    UILabel *monthLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0,100, 40)];
    [monthLabel setTextAlignment:NSTextAlignmentCenter];
    monthLabel.text = @"本月";
    [monthLabel setTextColor:[UIColor whiteColor]];
    [_monthBtn addSubview:monthLabel];
    
    UILabel *quarterLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    [quarterLabel setTextAlignment:NSTextAlignmentCenter];
    quarterLabel.text = @"本季度";
    [quarterLabel setTextColor:[UIColor whiteColor]];
    [_quarterBtn addSubview:quarterLabel];
    
    UILabel *yearLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100,40)];
    [yearLabel setTextAlignment:NSTextAlignmentCenter];
    yearLabel.text = @"本年";
    [yearLabel setTextColor:[UIColor whiteColor]];
    [_yearBtn addSubview:yearLabel];
    
    
    [self setupImage];
    [self.view addSubview:self.pieChartLeft];
    
    
    _startTimeLabel.userInteractionEnabled = YES;
    [_startTimeLabel bk_whenTapped:^{
        timePos = 0;
        self.pmCC = [[PMCalendarController alloc] initWithThemeName:@"default"];
        self.pmCC.delegate = self;
        self.pmCC.mondayFirstDayOfWeek = NO;
        if ([self.pmCC isCalendarVisible])
        {
            [self.pmCC dismissCalendarAnimated:NO];
        }
       
        [self.pmCC presentCalendarFromView:_startTimeLabel
                  permittedArrowDirections:PMCalendarArrowDirectionAny
                                 isPopover:YES
                                  animated:YES];
         self.pmCC.period = [PMPeriod oneDayPeriodWithDate:startDate];
        
    }];

    
    _endTimeLabel.userInteractionEnabled = YES;
    [_endTimeLabel bk_whenTapped:^{
        timePos = 1;
        self.pmCC = [[PMCalendarController alloc] initWithThemeName:@"default"];
        self.pmCC.delegate = self;
        self.pmCC.mondayFirstDayOfWeek = NO;
        if ([self.pmCC isCalendarVisible])
        {
            [self.pmCC dismissCalendarAnimated:NO];
        }
        
        [self.pmCC presentCalendarFromView:_endTimeLabel
                  permittedArrowDirections:PMCalendarArrowDirectionAny
                                 isPopover:YES
                                  animated:YES];
        self.pmCC.period = [PMPeriod oneDayPeriodWithDate:endDate];

       
        
    }];
    
    
    [_startTimeLabel setText:[DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDD]];
    [_endTimeLabel setText:[DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDD]];
    [self setStatisticsData:[NSString stringWithFormat:@"%@",_startTimeLabel.text] andEndDate:[NSString stringWithFormat:@"%@ 23:59:59",_endTimeLabel.text]];
    
    
    [_monthBtn bk_whenTapped:^{
        NSString *last =[DateUtils dateToStringByFormat:
                         [NSDate dateWithTimeIntervalSince1970:[DateUtils getLastDayOfMonth:[[NSDate date] timeIntervalSince1970]*1000]/1000] format:YYYYMMDD];
        NSString *first =[DateUtils dateToStringByFormat:
                    [NSDate dateWithTimeIntervalSince1970:[DateUtils getFirstDayOfMonth:[[NSDate date] timeIntervalSince1970]*1000]/1000] format:YYYYMMDD];
        
        [_startTimeLabel setText:first];
        [_endTimeLabel setText:last];
        [self setStatisticsData:[NSString stringWithFormat:@"%@",_startTimeLabel.text] andEndDate:[NSString stringWithFormat:@"%@ 23:59:59",_endTimeLabel.text]];
        
    }];
    
    [_quarterBtn bk_whenTapped:^{
        NSString *last =[DateUtils dateToStringByFormat:
                         [NSDate dateWithTimeIntervalSince1970:[DateUtils getLastDayOfQuarter:[[NSDate date] timeIntervalSince1970]*1000]/1000] format:YYYYMMDD];
        NSString *first =[DateUtils dateToStringByFormat:
                          [NSDate dateWithTimeIntervalSince1970:[DateUtils getFirstDayOfQuarter:[[NSDate date] timeIntervalSince1970]*1000]/1000] format:YYYYMMDD];
        
        [_startTimeLabel setText:first];
        [_endTimeLabel setText:last];
        [self setStatisticsData:[NSString stringWithFormat:@"%@",_startTimeLabel.text] andEndDate:[NSString stringWithFormat:@"%@ 23:59:59",_endTimeLabel.text]];
    }];
    
    
    [_yearBtn bk_whenTapped:^{
        NSString *last =[DateUtils dateToStringByFormat:
                         [NSDate dateWithTimeIntervalSince1970:[DateUtils getLastDayOfYear:[[NSDate date] timeIntervalSince1970]*1000]/1000] format:YYYYMMDD];
        NSString *first =[DateUtils dateToStringByFormat:
                          [NSDate dateWithTimeIntervalSince1970:[DateUtils getFirstDayOfYear:[[NSDate date] timeIntervalSince1970]*1000]/1000] format:YYYYMMDD];
        
        [_startTimeLabel setText:first];
        [_endTimeLabel setText:last];
        [self setStatisticsData:[NSString stringWithFormat:@"%@",_startTimeLabel.text] andEndDate:[NSString stringWithFormat:@"%@ 23:59:59",_endTimeLabel.text]];
    }];
}

-(void)setupImage
{
    self.pieChartLeft = [[XYPieChart alloc] initWithFrame:CGRectMake(120, 120, 400, 400)];
    [self.pieChartLeft setDataSource:self];
    [self.pieChartLeft setDelegate:self];
    [self.pieChartLeft setStartPieAngle:M_PI_2];
    [self.pieChartLeft setAnimationSpeed:1.0];
    [self.pieChartLeft setLabelFont:[UIFont fontWithName:@"DBLCDTempBlack" size:24]];
    [self.pieChartLeft setLabelRadius:160];
    [self.pieChartLeft setShowPercentage:YES];
    [self.pieChartLeft setPieBackgroundColor:[UIColor colorWithWhite:0.95 alpha:1]];
    [self.pieChartLeft setPieCenter:CGPointMake(240, 240)];
    [self.pieChartLeft setUserInteractionEnabled:NO];
    [self.pieChartLeft setLabelShadowColor:[UIColor blackColor]];
}


- (NSUInteger)numberOfSlicesInPieChart:(XYPieChart *)pieChart1
{
    return 3;
}
- (CGFloat)pieChart:(XYPieChart *)pieChart valueForSliceAtIndex:(NSUInteger)index
{
    if(datas && [datas count])
    {
        return [[datas objectAtIndex:index] floatValue];
    }
    return 0;
}

- (UIColor *)pieChart:(XYPieChart *)pieChart colorForSliceAtIndex:(NSUInteger)index
{
    return [self.sliceColors objectAtIndex:index];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    LKDBHelper *helper  = [LKDBHelper getUsingLKDBHelper];
    array = [helper search:[PayModel class] where:nil orderBy:nil offset:0 count:0];
    if(array!=nil)
        return [array count];
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 NSString *reuseIdetify = @"StatCell";
    StatCell  *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
    if(!cell){
        
        
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"StatCell" owner:self options:nil];
        for(id oneObject in nib){
            if([oneObject isKindOfClass:[StatCell class]]){
                cell = (StatCell *) oneObject;
            }
        }
        
    }
    PayModel *model = [array objectAtIndex:indexPath.row];
    cell.detailsLabel.text = @"详细";
    [cell.detailsLabel setTextColor:[UIColor blueColor]];
    
    LKDBHelper *helper  = [LKDBHelper getUsingLKDBHelper];
    PayTypeModel *type = [helper searchSingle:[PayTypeModel class] where:[NSString stringWithFormat:@"t_id=%ld",(long)model.payTypeId] orderBy:nil];
    cell.fenleiLabel.text = type.payTypeName;
    
    cell.moneyLabel.text = [NSString stringWithFormat:@"%0.2f",model.money];
    
    return cell;

}

#pragma mark PMCalendarControllerDelegate methods

- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    
//    nowDate=newPeriod.startDate;
//    dateLabel.text = [NSString stringWithFormat:@"%@"
//                      , [newPeriod.startDate dateStringWithFormat:@"yyyy-MM-dd"]];
    
    if(timePos==0)
    {
       // NSString *nowDate=newPeriod.startDate;
        _startTimeLabel.text = [NSString stringWithFormat:@"%@"
                              , [newPeriod.startDate dateStringWithFormat:@"yyyy-MM-dd"]];
        startDate = newPeriod.startDate;
        
    }else
    {
        _endTimeLabel.text = [NSString stringWithFormat:@"%@"
                                , [newPeriod.startDate dateStringWithFormat:@"yyyy-MM-dd"]];
        endDate = newPeriod.endDate;
    }
    
    [self setStatisticsData:[NSString stringWithFormat:@"%@",_startTimeLabel.text] andEndDate:[NSString stringWithFormat:@"%@ 23:59:59",_endTimeLabel.text]];
}


-(void)setStatisticsData:(NSString *)startDate andEndDate:(NSString *)endDate
{
    NSMutableArray *jinhuoArray = [AddProductModel searchWithWhere:[NSString stringWithFormat:@"createDate>='%@' and createDate<='%@'",startDate,endDate] orderBy:nil offset:0 count:0];
    
    int sumjinhuo=0;
    float moneyjinhuo=0;
    if(jinhuoArray && [jinhuoArray count])
    {
        
        for (AddProductModel *model in jinhuoArray) {
            sumjinhuo =sumjinhuo +model.productNumber;
            moneyjinhuo = moneyjinhuo+model.productNumber *model.buyPrice;
        }
        
        _jinhuoLabel.text = [NSString stringWithFormat:@"进货:%d",sumjinhuo];
        _jinhuomoneyLabel.text = [NSString stringWithFormat:@"金额:%0.2f ￥",moneyjinhuo];
    }
    
    float sumZhichuMoney =0;
    NSMutableArray *zhichuArray = [PayModel searchWithWhere:[NSString stringWithFormat:@"date>='%@' and date<='%@'",startDate,endDate] orderBy:nil offset:0 count:0];
    if(zhichuArray && [zhichuArray count]>0)
    {
        
        _zhichuLabel.text = [_zhichuLabel.text replaceCharcter:@"%@" withCharcter:[NSString stringWithFormat:@"%d",zhichuArray.count]];
        for (PayModel *model in zhichuArray) {
            sumZhichuMoney += model.money;
        }
        
        _zhichumoneyLabel.text = [NSString stringWithFormat:@"金额:%0.2f￥",sumZhichuMoney];
    }

    
    NSMutableArray *chuhuoArray = [SaleOrderModel searchWithWhere:[NSString stringWithFormat:@"date>='%@' and date<='%@'",startDate,endDate] orderBy:nil offset:0 count:0];
    
    if(chuhuoArray)
    {
        int sumChuhuo =0;
        float countMoney = 0.0;
        for (SaleOrderModel *model in chuhuoArray) {
            sumChuhuo =sumChuhuo +model.totalNumber;
            countMoney =countMoney+model.totalPrice;
        }
        
        
        _chuhuoLabel.text = [NSString stringWithFormat:@"出货:%d件",sumChuhuo];
        _chuhuomoneyLabel.text = [NSString stringWithFormat:@"金额:%0.2f￥",countMoney];
        _countMoneyLabel.text = [NSString stringWithFormat:@"总营业额:%0.2f￥",countMoney];
        _countlirunLabel.text = [NSString stringWithFormat:@"总利润:%0.2f￥",countMoney-moneyjinhuo - sumZhichuMoney];
        
    }

    
    NSMutableArray *diaoboArray = [SaleOrderModel searchWithWhere:[NSString stringWithFormat:@"date>='%@' and date<='%@'",startDate,endDate] orderBy:nil offset:0 count:0];
    if(diaoboArray && [diaoboArray count])
    {
        int sumChuhuo =0;
        float countMoney = 0.0;
        for (SaleOrderModel *model in diaoboArray) {
            if(model.client && model.client.clientType == AccountTypeAllocate)
            {
                sumChuhuo=sumChuhuo+model.totalNumber;
                countMoney = countMoney+ model.totalPrice;
            }
          
        }
        
        
        _diaoboLabel.text = [NSString stringWithFormat:@"调拨:%d件",sumChuhuo];
        _diaobomoneyLabel.text = [NSString stringWithFormat:@"金额:%0.2f￥",countMoney];
    }
    
    
    float liruncountMoney = 0.0;
    NSMutableArray *lirunArray = [SaleOrderModel searchWithWhere:[NSString stringWithFormat:@"date>='%@' and date<='%@'",startDate,endDate] orderBy:nil offset:0 count:0];
    if(lirunArray && [lirunArray count])
    {
 
        for (SaleOrderModel *model in diaoboArray) {
            liruncountMoney =liruncountMoney+ model.totalPrice;
            
        }
        
        _lirunLabel.text = [NSString stringWithFormat:@"利润:%0.2f￥",liruncountMoney];
    }
    
    
    

    
    int sumCount = moneyjinhuo +sumZhichuMoney +liruncountMoney;
    float jinhuoP =0.0;
    float zhichuP = 0.0;
    float lirunP = 0.0;
    if(sumCount!=0)
    {
        jinhuoP = moneyjinhuo/sumCount *100;
        zhichuP = sumZhichuMoney/sumCount *100;
        lirunP = liruncountMoney/sumCount *100;
    }
   
    
    [datas removeAllObjects];
    [datas addObject:[NSNumber numberWithFloat:jinhuoP]];
    [datas addObject:[NSNumber numberWithFloat:zhichuP]];
    [datas addObject:[NSNumber numberWithFloat:lirunP]];
    
    NSLog(@"利润:%f %f %f",jinhuoP,zhichuP,lirunP);
    
    [_chenbenPerLabel setText:[NSString stringWithFormat:@"成本:%0.1f%%",jinhuoP]];
    [_zhichuPerLabel setText:[NSString stringWithFormat:@"支出:%0.1f%%",zhichuP]];
    [_lirunPerLabel setText:[NSString stringWithFormat:@"利润:%0.1f%%",lirunP]];
    
    [self.pieChartLeft reloadData];
   // [self.pieChartLeft reloadInputViews];
    
}



//-(void)reloadStatistData:(NSString *)startDate andEndDate:(NSString *)endDate
//{
//  //  NSMutableArray *datas = [AddProductModel searchWithWhere:[NSString stringWithFormat:@"createDate>%@ and createDate<%@",startDate,endDate] orderBy:nil offset:0 count:0];
//    double inPrices = [AddProductModel sumWithWhere:@"buyPrice" where:[NSString stringWithFormat:@"createDate>%@ and createDate<%@",startDate,endDate]];
//    double productNumber = [AddProductModel sumWithWhere:@"productNumber" where:[NSString stringWithFormat:@"createDate>%@ and createDate<%@",startDate,endDate]];
//    double outPrices = [PayModel sumWithWhere:@"money" where:[NSString stringWithFormat:@"createDate>%@ and createDate<%@",startDate,endDate]];
//    
//    NSMutableArray *payArray = [PayModel searchWithWhere:[NSString stringWithFormat:@"createDate>%@ and createDate<%@",startDate,endDate] orderBy:nil offset:0 count:0];
//    
//    
//    
//    
//    
//    
//}

@end
